<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <title>黄金实时行情</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: #1E1E1E;
            color: gold;
            font-family: "Microsoft YaHei", sans-serif;
        }
        .header {
            padding: 12px;
            border-bottom: 1px solid gold;
        }
        .header h1 { font-size: 18px; text-align: center; }
        .header .time {
            font-size: 12px;
            color: #ccc;
            text-align: right;
            margin-top: 5px;
        }
        .market-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0 60px; /* 底部留空间给按钮 */
        }
        .market-table th, .market-table td {
            border: 1px solid gold;
            padding: 8px;
            text-align: center;
        }
        .market-table th { background: #333; }
        .price-red { color: red; }
        .nav-btn, .setting-link {
            display: block;
            width: 90%;
            margin: 10px auto;
            padding: 10px;
            text-align: center;
            text-decoration: none;
            border-radius: 4px;
        }
        .nav-btn {
            background: gold;
            color: #1E1E1E;
        }
        .setting-link {
            background: #333;
            color: gold;
            border: 1px solid gold;
        }
        .footer {
            font-size: 12px;
            color: #ccc;
            line-height: 1.6;
            padding: 15px;
        }
        .qr-code {
            text-align: center;
            margin-top: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            padding: 10px 0;
        }
        .qr-code img {
            width: 120px;
            height: 120px;
            border: 2px solid gold;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            transition: transform 0.3s ease;
        }
        .qr-code img:hover {
            transform: scale(1.05);
        }

        /* 地址复制相关样式 */
        .address-container {
            display: inline-flex;
            align-items: center;
        }
        .address-text {
            margin-right: 5px;
        }
        .copy-btn {
            background: #444;
            color: gold;
            border: 1px solid gold;
            border-radius: 4px;
            padding: 2px 6px;
            font-size: 10px;
            cursor: pointer;
            white-space: nowrap;
        }
        .copy-btn:hover {
            background: #555;
        }
        .copy-success {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: gold;
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 1000;
            display: none;
        }

        /* 导航选择弹窗样式 */
        .nav-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .nav-content {
            background: #2d2d2d;
            border: 1px solid gold;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 300px;
        }
        .nav-title {
            color: gold;
            text-align: center;
            margin-bottom: 15px;
            font-size: 16px;
        }
        .nav-option {
            display: flex;
            align-items: center;
            padding: 12px;
            margin: 8px 0;
            background: #333;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .nav-option:hover {
            background: #444;
        }
        .nav-icon {
            width: 30px;
            height: 30px;
            border-radius: 6px;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        .amap { background: #4d90fe; }
        .baidu { background: #2932e1; }
        .tencent { background: #13bf72; }
        .apple { background: #000; }
        .close-btn {
            display: block;
            width: 100%;
            padding: 10px;
            margin-top: 15px;
            background: #555;
            color: #ccc;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<!-- 头部 -->
<div class="header">
    <h1><span id="title">王掌柜黄金</span>实时行情</h1>
    <div class="time" id="currentTime"></div>
</div>

<!-- 行情表格 -->
<table class="market-table">
    <thead><tr><th>商品</th><th>回购</th><th>销售</th></tr></thead>
    <tbody>
    <tr><td>黄金</td><td class="price-red" id="goldBuy"></td><td class="price-red" id="goldSell"></td></tr>
    <tr><td>18K</td><td class="price-red" id="k18Buy"></td><td class="price-red" id="k18Sell"></td></tr>
    <tr><td>铂金</td><td class="price-red" id="ptBuy"></td><td class="price-red" id="ptSell"></td></tr>
    <tr><td>钯金</td><td class="price-red" id="pdBuy"></td><td class="price-red" id="pdSell"></td></tr>
    <tr><td>白银</td><td class="price-red" id="agBuy"></td><td class="price-red" id="agSell"></td></tr>
    </tbody>
</table>

<!-- 功能按钮 -->
<a href="javascript:;" class="nav-btn" id="navBtn">一键导航到门店</a>
<a href="admin" class="setting-link">管理设置（需登录）</a>

<!-- 导航选择弹窗 -->
<div class="nav-modal" id="navModal">
    <div class="nav-content">
        <div class="nav-title">选择导航应用</div>
        <div class="nav-option" onclick="openAmap()">
            <div class="nav-icon amap">高</div>
            <div>高德地图</div>
        </div>
        <div class="nav-option" onclick="openBaiduMap()">
            <div class="nav-icon baidu">百</div>
            <div>百度地图</div>
        </div>
        <div class="nav-option" onclick="openTencentMap()">
            <div class="nav-icon tencent">腾</div>
            <div>腾讯地图</div>
        </div>
        <button class="close-btn" onclick="closeNavModal()">取消</button>
    </div>
</div>

<!-- 页脚信息 -->
<div class="footer">
    <p>声明：以上行情仅供参考！</p>
    <p>联系电话：<span id="phone"></span>（微信同号）</p>
    <p>主营业务：黄金、钻石、名烟名酒、奢侈品、等贵金属的回收与保管</p>
    <p>回收地址：<span id="address"></span><button class="copy-btn" onclick="copyAddress()">复制</button></p>
    <div class="qr-code">
        <!-- 动态显示二维码图片 -->
        <img id="qrCodeImage" src="" alt="二维码" />
    </div>
</div>

<!-- 复制成功提示 -->
<div id="copySuccess" class="copy-success">地址已复制到剪贴板</div>

<script>
    let dataAll;
    let userNameAll;
    let markups = {
        goldMarkup: 0,
        k18Markup: 0,
        ptMarkup: 0,
        pdMarkup: 0,
        agMarkup: 0
    };
    const params = getUrlParams();
    userNameAll = params.name
    chushihua()
    function chushihua(){
        // 使用fetch发起GET请求（也可使用axios等库）
        fetch('/app/getOne',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userNameAll
            })
        }) // 注意：此处URL需与后端一致
            .then(response => response.json())
            .then(data => {
                // console.log(data);
                dataAll = data.data;
                document.getElementById(`title`).innerText = dataAll.shopname;
                document.getElementById(`phone`).innerText = dataAll.phone;
                document.getElementById(`address`).innerText = dataAll.address;

                // 显示二维码图片
                displayQrCode(dataAll.qrCode);
            });
    }
    // 显示二维码图片
    function displayQrCode(qrCodeFileName) {
        const qrCodeImage = document.getElementById('qrCodeImage');

        if (qrCodeFileName) {
            // 获取当前页面的协议、主机和端口
            const protocol = window.location.protocol; // http: 或 https:
            const hostname = window.location.hostname; // 域名或IP
            const port = window.location.port;         // 端口号

            // 构建完整的图片URL
            let imageUrl;
            if (port) {
                imageUrl = `${protocol}//${hostname}:${port}${qrCodeFileName}`;
            } else {
                imageUrl = `${protocol}//${hostname}${qrCodeFileName}`;
            }

            // 设置图片源
            qrCodeImage.src = imageUrl;
            qrCodeImage.alt = '店铺二维码';
            qrCodeImage.style.display = 'block';

            // 调试信息（可选）
            console.log('二维码图片URL:', imageUrl);
            console.log('当前连接信息:', {
                protocol: protocol,
                hostname: hostname,
                port: port,
                fullURL: window.location.href
            });
        } else {
            // 如果没有二维码，显示默认提示或隐藏
            qrCodeImage.style.display = 'none';
        }
    }
    /**
     * 获取URL中的查询参数
     * @param {string} [url] - 可选参数，指定要解析的URL，默认使用当前页面URL
     * @returns {Object} 包含所有查询参数的对象
     */
    function getUrlParams(url) {
        // 如果没有提供URL，使用当前页面的URL
        const currentUrl = url || window.location.href;

        // 解析URL中的查询字符串部分
        const params = {};
        const queryString = currentUrl.split('?')[1];

        // 如果没有查询字符串，返回空对象
        if (!queryString) {
            return params;
        }

        // 分割查询字符串为键值对数组
        const keyValuePairs = queryString.split('&');

        // 解析每个键值对
        keyValuePairs.forEach(pair => {
            // 处理可能包含=的参数值
            const [key, ...valueParts] = pair.split('=');
            if (key) {
                // 解码URL编码的字符
                const decodedKey = decodeURIComponent(key);
                const decodedValue = valueParts.length > 0
                    ? decodeURIComponent(valueParts.join('='))
                    : '';
                params[decodedKey] = decodedValue;
            }
        });

        return params;
    }

    function loadUser() {
        // 使用fetch发起GET请求（也可使用axios等库）
        fetch('/app/getOne',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userNameAll
            })
        }) // 注意：此处URL需与后端一致
            .then(response => response.json())
            .then(data => {
                // console.log(data);
                dataAll = data.data;
                markups = {
                    goldMarkup: dataAll.gold,
                    k18Markup: dataAll.k18,
                    ptMarkup: dataAll.pt,
                    pdMarkup: dataAll.pd,
                    agMarkup: dataAll.ag
                };
            });
    }

    // ───────────────────────────────────────
    // 导航功能
    // ───────────────────────────────────────
    function showNavModal() {
        document.getElementById('navModal').style.display = 'flex';
    }

    function closeNavModal() {
        document.getElementById('navModal').style.display = 'none';
    }

    // 获取门店地址（从页脚信息中提取）
    function getShopAddress() {
        return document.getElementById('address').innerText || '北京市朝阳区望京SOHO';
    }

    // 调起高德地图
    function openAmap() {
        const destination = encodeURIComponent(getShopAddress());
        const url = `amapuri://route/plan/?dname=${destination}&dev=0&t=0`;

        // 尝试调起高德地图App
        window.location.href = url;

        // 如果调起失败，跳转到高德地图下载页
        setTimeout(function() {
            window.location.href = 'https://uri.amap.com/mobile';
        }, 500);

        closeNavModal();
    }

    // 调起百度地图
    function openBaiduMap() {
        const destination = encodeURIComponent(getShopAddress());
        const url = `baidumap://map/direction?destination=${destination}&mode=driving&coord_type=gcj02&src=webapp.baidu.openAPIdemo`;

        // 尝试调起百度地图App
        window.location.href = url;

        // 如果调起失败，跳转到百度地图下载页
        setTimeout(function() {
            window.location.href = 'https://map.baidu.com/zt/client/index/';
        }, 500);

        closeNavModal();
    }

    // 调起腾讯地图
    function openTencentMap() {
        const destination = encodeURIComponent(getShopAddress());
        const url = `qqmap://map/routeplan?type=drive&to=${destination}&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77`;

        // 尝试调起腾讯地图App
        window.location.href = url;

        // 如果调起失败，跳转到腾讯地图下载页
        setTimeout(function() {
            window.location.href = 'https://map.qq.com/m/';
        }, 500);

        closeNavModal();
    }

    // 绑定导航按钮点击事件
    document.getElementById('navBtn').onclick = showNavModal;

    // ───────────────────────────────────────
    // 地址复制功能
    // ───────────────────────────────────────
    // 复制地址到剪贴板
    function copyAddress() {
        const addressText = document.getElementById('address').innerText;

        // 使用现代浏览器的Clipboard API
        if (navigator.clipboard) {
            navigator.clipboard.writeText(addressText).then(() => {
                showCopySuccess();
            }).catch(err => {
                console.error('复制失败:', err);
                // 降级方案
                fallbackCopyTextToClipboard(addressText);
            });
        } else {
            // 降级方案
            fallbackCopyTextToClipboard(addressText);
        }
    }

    // 降级复制方案
    function fallbackCopyTextToClipboard(text) {
        const textArea = document.createElement("textarea");
        textArea.value = text;

        // 避免滚动到底部
        textArea.style.top = "0";
        textArea.style.left = "0";
        textArea.style.position = "fixed";

        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            const successful = document.execCommand('copy');
            if (successful) {
                showCopySuccess();
            } else {
                console.error('复制命令执行失败');
            }
        } catch (err) {
            console.error('复制失败:', err);
        }

        document.body.removeChild(textArea);
    }

    // 显示复制成功提示
    function showCopySuccess() {
        const successElement = document.getElementById('copySuccess');
        successElement.style.display = 'block';

        // 2秒后隐藏提示
        setTimeout(() => {
            successElement.style.display = 'none';
        }, 2000);
    }

    // ───────────────────────────────────────
    // 时间显示更新
    // ───────────────────────────────────────
    function updateTime() {
        const now = new Date();
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        };
        const timeStr = now.toLocaleString('zh-CN', options);
        const weekday = ['日', '一', '二', '三', '四', '五', '六'][now.getDay()];
        document.getElementById('currentTime').innerText = `${timeStr} | 星期${weekday} | 开盘中`;
    }
    // 初始化时间并定时更新
    updateTime();
    setInterval(updateTime, 1000);

    // ───────────────────────────────────────
    // 行情数据加载与渲染
    // ───────────────────────────────────────
    /** 加载行情数据（含加价计算） */
    async function loadMarketData() {
        try {
            // 1. 获取加价数据
            loadUser()

            // 2. 请求市场行情数据
            const res = await fetch('https://free.xwteam.cn/api/gold/trade');
            const data = await res.json();
            if (data.code !== 200) throw new Error(data.msg || '行情数据异常');

            // 3. 筛选现货市场（LF）的目标商品
            const LF = data.data.LF;
            const goodsMap = {
                Au: LF.find(item => item.Symbol === 'Au'),        // 黄金
                Au750Old: LF.find(item => item.Symbol === 'Au750Old'), // 18K
                Pt: LF.find(item => item.Symbol === 'Pt'),        // 铂金
                Pd: LF.find(item => item.Symbol === 'Pd'),        // 钯金
                Ag: LF.find(item => item.Symbol === 'Ag')         // 白银
            };
            console.log(goodsMap)
            // 4. 渲染各商品价格
            renderPrice('gold', goodsMap.Au);
            renderPrice('k18', goodsMap.Au750Old);
            renderPrice('pt', goodsMap.Pt);
            renderPrice('pd', goodsMap.Pd);
            renderPrice('ag', goodsMap.Ag);

        } catch (err) {
            console.error('行情加载失败:', err);
            alert('数据加载失败：' + err.message);
        }
    }

    /** 渲染单个商品价格（含加价） */
    function renderPrice(key, goods) {
        if (!goods) return;

        // 映射商品key到加价字段
        const markupKeyMap = {
            'gold': 'goldMarkup',
            'k18': 'k18Markup',
            'pt': 'ptMarkup',
            'pd': 'pdMarkup',
            'ag': 'agMarkup'
        };

        // 获取对应加价（默认0）
        const markup = markups[markupKeyMap[key]] || 0;

        // 计算并渲染价格（保留2位小数）
        const buyPrice = goods.BP === 0 ? '--' : (goods.BP + markup).toFixed(2);
        const sellPrice = goods.SP === 0 ? '--' : (goods.SP).toFixed(2);
        document.getElementById(`${key}Buy`).innerText = buyPrice;
        document.getElementById(`${key}Sell`).innerText = sellPrice;
    }

    // ───────────────────────────────────────
    // 初始化与定时刷新
    // ───────────────────────────────────────
    // 页面加载时初始化数据库并加载行情
    setInterval(loadMarketData, 3000)
</script>
</body>
</html>
